package com.atguigu.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edu.realtime.app.BaseStreamApp;
import com.edu.realtime.bean.TradeOrderBean;
import com.edu.realtime.common.Constant;
import com.edu.realtime.util.AtguiguUtil;
import com.edu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;

public class DwsTradeOrderWindow extends BaseStreamApp {
    public static void main(String[] args) {
        new DwsTradeOrderWindow().init(4003,2,"DwsTradeOrderWindow", Constant.TOPIC_DWD_TRADE_ORDER_DETAIL);
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        stream
                .map(new MapFunction<String, TradeOrderBean>() {
                    @Override
                    public TradeOrderBean map(String value) throws Exception {
                        JSONObject obj = JSON.parseObject(value);
                        return TradeOrderBean.builder()
                                .orderIdSet(new HashSet<>(Collections.singletonList(obj.getString("order_id"))))
                                .userIdSet(new HashSet<>(Collections.singletonList(obj.getString("user_id"))))
                                .orderAmount(obj.getBigDecimal("final_amount"))
                                .ts(obj.getLong("ts")*1000)
                                .build();
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TradeOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean,ts) -> bean.getTs())
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TradeOrderBean>() {
                            @Override
                            public TradeOrderBean reduce(TradeOrderBean value1, TradeOrderBean value2) throws Exception {
                                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                                value1.getOrderIdSet().addAll(value2.getOrderIdSet());
                                value1.getUserIdSet().addAll(value2.getUserIdSet());
                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
                            @Override
                            public void process(Context context, Iterable<TradeOrderBean> elements, Collector<TradeOrderBean> out) throws Exception {
                                TradeOrderBean bean = elements.iterator().next();
                                bean.setStt(AtguiguUtil.toDateTime(context.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(context.window().getEnd()));
                                bean.setOrderCount((long) bean.getOrderIdSet().size());
                                bean.setOrderUserCount((long) bean.getUserIdSet().size());
                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);
                            }
                        })
                .addSink(FlinkSinkUtil.getClickHourseSink("dws_trade_order_window",TradeOrderBean.class));
    }
}
